package site.mingdao.boot.web.plugin.log.core.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import site.mingdao.boot.common.util.servlet.ServletUtils;

import java.util.Map;

/**
 * API 访问日志 Interceptor
 */
@Slf4j
public class AccessLogInterceptor implements HandlerInterceptor {

    private static final String ATTRIBUTE_STOP_WATCH = "ApiAccessLogInterceptor.StopWatch";

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        String requestURI = request.getRequestURI();
        if (skipDoc(requestURI)) return true;
        // 打印 request 日志
        Map<String, String> queryString = ServletUtils.getParamMap(request);
        String requestBody = ServletUtils.isJsonRequest(request) ? ServletUtils.getBody(request) : null;
        if (CollUtil.isEmpty(queryString) && StrUtil.isEmpty(requestBody)) {
            log.info("[开始请求 URL:{} 无参数]", requestURI);
        } else {
            log.info("[开始请求 URL:{} 参数:{}]", requestURI, StrUtil.blankToDefault(requestBody, queryString.toString()));
        }
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        request.setAttribute(ATTRIBUTE_STOP_WATCH, stopWatch);
        return true;
    }

    @Override
    public void afterCompletion(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler, Exception ex) {
        String requestURI = request.getRequestURI();
        if (!skipDoc(requestURI)) {
            // 打印 response 日志
            StopWatch stopWatch = (StopWatch) request.getAttribute(ATTRIBUTE_STOP_WATCH);
            stopWatch.stop();
            log.info("[完成请求 URL:{} 耗时:{}ms]", request.getRequestURI(), stopWatch.getTotalTimeMillis());
        }
    }

    private boolean skipDoc(String requestURI) {
        return StrUtil.contains(requestURI, "/webjars") || StrUtil.contains(requestURI, "/v3/api-docs");
    }

}
